package com.jmars.TS.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jmars.TS.common.AjaxResult;
import com.jmars.TS.common.JiumiConfig;
import com.jmars.TS.entity.PublicParams;
import com.jmars.TS.mapper.db1.WMSInOutMapper;
import com.jmars.TS.service.*;
import com.jmars.TS.util.DateUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * 野村调用WMS接口
 * @Author: cly
 * @DateTime: 2021/12/22 11:12
 * @msg:
 */

@CrossOrigin
@RestController
@RequestMapping("/wms")
public class WmsController {
    private static final Logger logger = LoggerFactory.getLogger(WmsController.class);

    /** 系统基础配置 */
    @Autowired
    private JiumiConfig jiumiConfig;

    @Autowired
    WmsService wmsService;


    //http://127.0.0.1:8057/api/getStandardVersion
    @ResponseBody
    @RequestMapping(value = "/wms/getStandardVersion")
    public String getStandardVersion(){
        return "1.0";
    }

    //http://127.0.0.1:8057/api/getVendorVersion
    @ResponseBody
    @RequestMapping(value = "/wms/getVendorVersion")
    public String getVendorVersion(){

        return "1.0.1.20241022";
    }



    @Autowired
    WMSInOutMapper wmsInOutMapper;

    // 1、商品主档
    //http://127.0.0.1:8057/wms/callApiCenter
    @PostMapping("/callApiCenter")
    public AjaxResult callApiCenter(@RequestBody PublicParams pp){

        //  url:http://172.24.133.89:9999/apiPortal/callApiCenter, body====> {"companyCd":"0903458423","signature":"49B7D72A03AF06A7","apiService":"getWmsStoreReturnList","body":"{\"vendorId\":\"000379\"}","timestamp":"20250307105143"}
        logger.info("callApiCenter post  param ====> {}", pp.toString());


//        {
//            "companyCd": "0903458423",
//                "signature": "BAE475D9E0E64A7A",
//                "apiService": "getWmsStoreReturnList",
//                "body": "{\"vendorId\":\"000379\"}",
//                "timestamp": "20250317143943"
//        }
        AjaxResult ajaxResult = new AjaxResult("500", "error", null);

        try {

            String strCompanyCd = pp.getCompanyCd();
            String strTimestamp = pp.getTimestamp();
            String strApiService = pp.getApiService();
            String strBody = pp.getBody();
            String strSignature = pp.getSignature();

            // 参数
            PublicParams params = new PublicParams();
            params.setCompanyCd(strCompanyCd);
            params.setTimestamp(strTimestamp);
            params.setApiService(strApiService);
            params.setBody(strBody);
            String strSign = Md5Sign(jiumiConfig.getSecreteKey(), JSON.toJSONString(params)); // 签数签名

            params.setCompanyCd(jiumiConfig.getCompanyCd());

            // 判断账号权限
            if (StringUtils.isEmpty(strCompanyCd) || !strCompanyCd.equals(jiumiConfig.getCompanyCd())) {
                return AjaxResult.error("60001", "公司或API没有授权", null);
            }

            // 将时间戳字符串转换为 Date 对象
            Date timestampDate = DateUtils.dateTime("yyyyMMddHHmmss", strTimestamp);

            // 获取当前时间
            Date now = new Date();

            // 计算时间差（分钟）
            long minutesDifference = (now.getTime() - timestampDate.getTime()) / (60 * 1000);

            // 判断时间差是否在15分钟内
            if (minutesDifference > 15) {
                return AjaxResult.error("60002", "请求参数 timestamp 与服务器时间不在 15 分钟内", null);
            }

            // debug
            //strSignature = strSign;

            // 判断签名
            if (!strSignature.equals(strSign)) {
                return AjaxResult.error("60003", "签名不正确", null);
            }

            params.setSignature(strSign);
            String strJsonParams = JSON.toJSONString(params);

            // 判断API接口
            ajaxResult = new AjaxResult("60004", "未找到相关API服务", null);

            // 3.1、获取供应商退库商品库存
            if (strApiService.equals("getWmsStoreReturnList")) {
                ajaxResult = wmsService.getWmsStoreReturnList(strBody);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            ajaxResult = new AjaxResult("500", "error !"+e.getMessage(), null);

        }

        logger.info("callApiCenter post  result ====> {}", JSON.toJSONString(ajaxResult));
        return ajaxResult;

    }


    // Method to sort JSON keys and concatenate key-value pairs
    public static String Md5Sign(String secreteKey ,String jsonStr) {
        // Parse JSON string into JSONObject
        JSONObject jsonObject = JSON.parseObject(jsonStr);

        // Create a TreeMap to sort keys in ascending ASCII order
        TreeMap<String, Object> sortedMap = new TreeMap<>();
        for (String key : jsonObject.keySet()) {
            sortedMap.put(key, jsonObject.get(key));
        }

        // Concatenate key-value pairs
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> entry : sortedMap.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            sb.append(key).append(value.toString());
        }

        String contentName = secreteKey + sb.toString() + secreteKey;
        String md5str = DigestUtils.md5Hex(contentName);; // 加密后md5
        // 加密后的字符串
//        String md5str = DigestUtils.md5Hex(text);
        //32位，小写
        String md532Lower = md5str.toString();
        //32位，大写
//        String md532Upper=md532Lower.toUpperCase();
        //16位，小写
//        String md516Lower =md532Lower.substring(8, 24);
        //16位，大写
        String md516Upper=md532Lower.substring(8, 24).toUpperCase();

        return md516Upper;
    }

}
